import 'dart:ui';

import 'package:flutter/rendering.dart';
import 'package:path_drawing/path_drawing.dart';

class HanziTransform{
  /// 字体基准尺寸
  static const _basisSize = 1024.0;

  ///笔划转Path
  static List<Path> transformStrokePathList(Map<dynamic, dynamic> chineseData) {
    List<Path> pathList = [];
    for (var i = 0; i < chineseData['strokes'].length; ++i) {
      var o = chineseData['strokes'][i];
      pathList.add(parseSvgPathData(o));
    }
    return pathList;
  }

  ///骨骼点转metric
  static List<PathMetric> transformMetricList(Map<dynamic, dynamic> chineseData) {
    List<PathMetric> metricList = [];
    for (var i = 0; i < chineseData['medians'].length; ++i) {
      var median = chineseData['medians'][i];
      Path path = Path();
      path.moveTo(median[0][0], median[0][1]);

      for (var j = 1; j < median.length; ++j) {
        var o = median[j];
        path.lineTo(o[0], o[1]);
      }
      var metric = path.computeMetrics().first;
      // print("$i.length:${metric.length}");
      metricList.add(metric);
    }
    return metricList;
  }

  ///矫正svg坐标和中线点坐标
  static void transformData(Map<dynamic, dynamic> chineseData, {double scale = 1}) {
    List<String> stroke = chineseData['strokes'].cast<String>();
    List medians = chineseData['medians'];
    const double deviationY = 120;
    String splitChar = ' ';
    bool isY = false; // 是不是y坐标
    for (int i = 0; i < stroke.length; i++) {
      String path = stroke[i];
      List<String> pathItems = path.split(splitChar);
      for (int i = 0; i < pathItems.length; i++) {
        if (pathItems[i].contains(RegExp(r"[a-zA-Z]"))){
          continue;
        }
        try {
          double num = double.parse(pathItems[i]);
          if (isY) {
            isY = false;
            num = _basisSize - num - deviationY;
          } else {
            isY = true;
          }
          pathItems[i] = (num * scale).toString();
        } catch (e) {
          debugPrint(e.toString());
        }
      }
      stroke[i] = pathItems.join(splitChar);
    }

    ///矫正中线坐标
    for (var median in medians) {
      for (var dot in median) {
        dot[0] = dot[0] * scale;
        dot[1] = (_basisSize - dot[1] - deviationY) * scale;
      }
    }
  }
}